//
// Created by de on 3/29/21.
//

#include "TPrepareState.h"
#include "thread"
E_State TPrepareState::init() {
    throw PlaformTException(__LINE__,__FILE__, "Mode Error"+std::to_string(state));
}

E_State TPrepareState::prepare() {
//    spdlog::info("prepare running ");
//    std::this_thread::sleep_for(std::chrono::seconds(1));
//    node->sendDevicePrepare();
    return Normal;

}

E_State TPrepareState::start() {
    node->sendDeviceEnable();
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    throw PlaformTException(__LINE__,__FILE__, "Mode Error"+std::to_string(state));
}

E_State TPrepareState::reset() {
    E_State eState = Normal;
    bool CheckRet = false;
    //判断异常类型
    ForceStateData data = node->getDeviceControlStateStatus();
    switch (data.errCodeInfoData.Err_level){
        //不可恢复异常
        case 1:
            throw PlaformTException(__LINE__,__FILE__, "不可恢复异常"+data.errCodeInfoData.Err_stringInfo);
            //可恢复异常
        default:
            CheckRet = node->sendDeviceCheck();
            break;
    }
    if(!CheckRet)
    {
        eState = node->sendDeviceReset() == true? Normal: Error;
    }


    return eState;
}

E_State TPrepareState::stop() {
    node->sendDeviceStop();
    throw PlaformTException(__LINE__,__FILE__, "Mode Error"+std::to_string(state));
}

StateStatus TPrepareState::getCurrentState() {
    return state;
}

E_State TPrepareState::wait() {
    ForceCtlStatus status ;
    int count = 0;
    spdlog::info("循环监听Wait状态中");
    do{
        status = node->getDeviceControlStateStatus().status;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        count++;

        if(status == Wait )
            break;
        if(status == Err ||status == Stop||count > 1000)
            return Error;

    }while (true);
    spdlog::info("循环监听结束");

    if(count > 1000)
        PlaformTException(__LINE__,__FILE__, "wait Time out ");

    node->sendDeviceEnable();

    return Normal;
}
